<?php
session_start();

require_once('../configs/common.php'); 	 
require_once("../configs/db_connect.php");
require_once('../models/Mail.class.php');

if ($_POST['action']=="get_messages")
{
	 $mail = new Mail();
	 header('Content-Type: application/json');
	 echo json_encode($mail->getMessages());
}

if ($_POST['action']=="count_unread_messages")
{
	 $response=array();
	 $response['count'] = Mail::countUnreadMessages();
	 header('Content-Type: application/json');
	 echo json_encode($response);
}

if ($_POST['action']=="update_messages_status")
{
	 $request_data=safe_var_Array(json_decode($_POST['data']), true);
	 Mail::updateMessageReadStatus($request_data['receiver'],$request_data['sender']);
}

if ($_POST['action']=="get_messages_conversation")
{
	 $response=array();
     $request_data=safe_var_Array(json_decode($_POST['data']), true);
	 $mail = Mail::getMessageConversation($request_data['receiver'],$request_data['sender']);
	 if ($mail)
	 {
		 $response=$mail;
	 }
	 else
	 {
		 $response['status']='no messages';
	 }
	 
	 header('Content-Type: application/json');
	 echo json_encode($response);
}

if ($_POST['action']=="send_message")
{
	 $response=array();
     $request_data=safe_var_Array(json_decode($_POST['data']), true);
	 $result = Mail::sendMessage($request_data['receiver_id'],$request_data['message']);
	 if ($result)
	 {
		 $response['status']='message sent';
	 }
	 else
	 {
		 $response['status']='message hasnt been send';
	 }
	 header('Content-Type: application/json');
	 echo json_encode($response);
}